import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import { initModelValue, renderForm, type FormModalDto } from '@/components/modal/Modal'
import {
    ExcelRuleCnEnum,
    getKeyToEnum,
    InsureTypeCnEnum,
    IsSetUserDetailConfigTypeCnEnum,
    ProductTypeCnEnum
} from '@/const/enum'
import {
    VxeColumn,
    VxeTable,
    type VxeColumnSlots,
    type VxeTableDataRow,
    type VxeTableProps,
    type VxeTablePropTypes
} from 'vxe-table'
import Upload from '@/components/file/Upload'
import InputList from '@/components/low-code/components/InputList'
import { Button, Form, FormItem, message, Select, TimePicker } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { h } from 'vue'
import type {
    CommunicationConfigDto,
    ConfigListDto,
    EmailConfigListDto
} from '@/api/emailConfig/types'
interface EmailRuleDto {
    fileTemplate: string[]
    emailTitleTemplate: string
    emailTextTemplate: string
    emailTo: string[]
}

@Component({
    emits: ['submit']
})
export class EmailRule extends Render {
    formData = {
        emailConfigs: [] as EmailConfigListDto[],
        coInsureType: IsSetUserDetailConfigTypeCnEnum.不配置,
        coInsureTime: '',
        coInsureEmail: '',
        coInsureEmailList: ['']
    }

    tableData = [
        {
            fileTemplate: [],
            emailTitleTemplate: '',
            emailTextTemplate: '',
            emailTo: ['']
        }
    ] as EmailRuleDto[]

    editConfig = {
        mode: 'row',
        trigger: 'click'
    } as VxeTablePropTypes.EditConfig

    uploadPrams = {
        accept: '.xlsx,.xls',
        autoUpload: true,
        base64: false,
        limit: 10
    }

    onAddRule() {
        this.tableData.push({
            fileTemplate: [],
            emailTitleTemplate: '',
            emailTextTemplate: '',
            emailTo: ['']
        })
    }

    handleSelectChange() {
        // 客户清单为不配置时清空数据
        if (this.formData.coInsureType === IsSetUserDetailConfigTypeCnEnum.不配置) {
            this.formData.coInsureTime = ''
            this.formData.coInsureEmailList = ['']
            this.formData.coInsureEmail = ''
        }
    }

    async createData(): Promise<EmailConfigListDto[]> {
        return new Promise((resolve, reject) => {
            const data = this.tableData.map((i) => {
                return {
                    fileTemplate: i.fileTemplate?.join(';'),
                    emailTitleTemplate: i.emailTitleTemplate,
                    emailTextTemplate: i.emailTextTemplate,
                    emailTo: i.emailTo?.join(';')
                }
            })
            if (
                data.some(
                    (i) =>
                        !i.fileTemplate ||
                        !i.emailTitleTemplate ||
                        !i.emailTextTemplate ||
                        !i.emailTo
                )
            ) {
                message.error('请填写完整')
                reject(false)
            } else {
                resolve(data)
            }
        })
    }

    initData(data: CommunicationConfigDto) {
        if (data.emailConfig?.length) {
            this.tableData = data.emailConfig.map((i: EmailConfigListDto) => {
                return {
                    ...i,
                    emailTo: i.emailTo.split(','),
                    fileTemplate: i.fileTemplate.split(',')
                }
            })
            this.formData.coInsureType = Number(data.coInsureType)
            if (Number(data.coInsureType) === IsSetUserDetailConfigTypeCnEnum.配置) {
                this.formData.coInsureTime = data.coInsureTime
                this.formData.coInsureEmail = data.coInsureEmail
                this.formData.coInsureEmailList = data.coInsureEmail?.split(';') ?? []
            }
        }
    }

    async submit() {
        this.formData.emailConfigs = await this.createData()
        this.formData.coInsureEmail = this.formData.coInsureEmailList.join(';')
        const { coInsureEmailList, ...otherData } = this.formData
        return otherData
    }

    render() {
        return (
            <>
                <div class="text-lg text-black-300 mb-20px">邮件推送规则</div>
                <div class="px-20px">
                    <Form class="w-full">
                        <FormItem label="发送规则" name="pushRule">
                            <div class="w-full">
                                <VxeTable data={this.tableData} border editConfig={this.editConfig}>
                                    <VxeColumn type="seq" width={60}></VxeColumn>
                                    <VxeColumn
                                        title="邮件模板"
                                        width={100}
                                        field="template"
                                        v-slots={{
                                            default: ({ row }: VxeTableDataRow) => {
                                                return (
                                                    <Upload
                                                        class="flex items-center justify-center py-5px"
                                                        v-model={row.fileTemplate}
                                                        multiple={true}
                                                        params={this.uploadPrams}
                                                        v-slots={{
                                                            default: () => {
                                                                return (
                                                                    <Button size="small">
                                                                        选择文件
                                                                    </Button>
                                                                )
                                                            }
                                                        }}
                                                    ></Upload>
                                                )
                                            }
                                        }}
                                    ></VxeColumn>
                                    <VxeColumn
                                        title="邮箱标题"
                                        field="emailTitleTemplate"
                                        editRender={{ name: 'input' }}
                                    ></VxeColumn>
                                    <VxeColumn
                                        title="邮件正文"
                                        field="emailTextTemplate"
                                        editRender={{ name: 'input' }}
                                    ></VxeColumn>
                                    <VxeColumn
                                        title="邮箱地址"
                                        field="emailTo"
                                        v-slots={{
                                            default: ({ row }: VxeTableDataRow) => {
                                                return <InputList v-model={row.emailTo}></InputList>
                                            }
                                        }}
                                    ></VxeColumn>
                                </VxeTable>
                                <Button
                                    icon={h(PlusOutlined)}
                                    class="w-full mt-10px"
                                    onClick={this.onAddRule}
                                >
                                    添加
                                </Button>
                            </div>
                        </FormItem>
                        <FormItem label="客户清单" name="clientList">
                            <div>
                                <div class="flex items-baseline flex-wrap mb-20px">
                                    <Select
                                        v-model:value={this.formData.coInsureType}
                                        class="!w-120px pr-5px"
                                        options={getKeyToEnum(IsSetUserDetailConfigTypeCnEnum)}
                                        onChange={this.handleSelectChange}
                                    ></Select>
                                    {this.formData.coInsureType ===
                                        IsSetUserDetailConfigTypeCnEnum.配置 && (
                                        <>
                                            <span>发送新增客户清单，每天</span>
                                            <TimePicker
                                                v-model:value={this.formData.coInsureTime}
                                                format="HH:mm:ss"
                                                valueFormat="HH:mm:ss"
                                                class="!w-120px mx-5px"
                                            ></TimePicker>
                                            <span>发送；</span>
                                        </>
                                    )}
                                </div>
                                {this.formData.coInsureType ===
                                    IsSetUserDetailConfigTypeCnEnum.配置 && (
                                    <>
                                        <FormItem label="邮箱地址" name="coInsureEmailList">
                                            <InputList
                                                v-model={this.formData.coInsureEmailList}
                                            ></InputList>
                                        </FormItem>
                                        <span class="text-sm text-black-300">
                                            最多可添加10个邮箱地址
                                        </span>
                                    </>
                                )}
                            </div>
                        </FormItem>
                    </Form>
                </div>
            </>
        )
    }
}

export default toNative<{}, {}>(EmailRule)
